import os
import sys
import asyncio
from typing import Dict, Any, Optional
from fastmcp import FastMCP
from pydantic import BaseModel

# 导入OrchestratorAgent
from src.agents.orchestrator_agent import OrchestratorAgent

# 初始化FastMCP服务器
mcp = FastMCP("financial_agent_mcp_server")

# 初始化主控Agent
orchestrator = OrchestratorAgent()

# 定义请求模型
class AnalysisRequest(BaseModel):
    symbol: str
    
class IndustryRequest(BaseModel):
    industry: str
    
class RiskRequest(BaseModel):
    analysis_data: str
    
class AdviceRequest(BaseModel):
    analysis_data: str

class MarketRequest(BaseModel):
    symbol: Optional[str] = None

# 注册工具函数
@mcp.tool()
def fundamental_analysis(symbol: str) -> dict:
    """
    公司基本面分析工具
    
    Args:
        symbol: 股票代码或公司名称
        
    Returns:
        包含基本面分析结果的字典
    """
    try:
        result = orchestrator.process_request(symbol, "基本面研究")
        return {"status": "success", "data": result}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
def industry_analysis(industry: str) -> dict:
    """
    行业研究分析工具
    
    Args:
        industry: 行业名称
        
    Returns:
        包含行业分析结果的字典
    """
    try:
        result = orchestrator.process_request(industry, "行业研究")
        return {"status": "success", "data": result}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
def macro_analysis() -> dict:
    """
    宏观经济分析工具
    
    Returns:
        包含宏观经济分析结果的字典
    """
    try:
        result = orchestrator.process_request("", "宏观研究")
        return {"status": "success", "data": result}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
def market_observation(symbol: Optional[str] = None) -> dict:
    """
    市场观察工具
    
    Args:
        symbol: 可选的股票代码，如果不提供则进行整体市场观察
        
    Returns:
        包含市场观察结果的字典
    """
    try:
        result = orchestrator.process_request(symbol or "", "市场观察")
        return {"status": "success", "data": result}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
def risk_assessment(analysis_data: str) -> dict:
    """
    投资风险评估工具
    
    Args:
        analysis_data: 需要进行风险评估的分析数据
        
    Returns:
        包含风险评估结果的字典
    """
    try:
        result = orchestrator.process_request(analysis_data, "风控")
        return {"status": "success", "data": result}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
def investment_advice(analysis_data: str) -> dict:
    """
    投资建议生成工具
    
    Args:
        analysis_data: 基于的分析数据
        
    Returns:
        包含投资建议的字典
    """
    try:
        result = orchestrator.process_request(analysis_data, "顾问")
        return {"status": "success", "data": result}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
def full_analysis(symbol: str) -> dict:
    """
    全流程金融分析工具
    
    Args:
        symbol: 股票代码或公司名称
        
    Returns:
        包含完整分析流程结果的字典
    """
    try:
        result = orchestrator.process_request(symbol, "全流程")
        return {"status": "success", "data": result}
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
def get_financial_data(symbol: str, data_type: str = "price") -> dict:
    """
    获取金融数据工具
    
    Args:
        symbol: 股票代码
        data_type: 数据类型 (price, volume, fundamentals)
        
    Returns:
        包含金融数据的字典
    """
    try:
        # 这里可以集成真实的金融数据API
        # 目前返回模拟数据
        mock_data = {
            "price": {
                "current": 100.50,
                "change": 2.30,
                "change_percent": 2.34,
                "volume": 1000000
            },
            "volume": {
                "current": 1000000,
                "avg_volume": 850000,
                "volume_ratio": 1.18
            },
            "fundamentals": {
                "pe_ratio": 15.6,
                "pb_ratio": 2.1,
                "roe": 0.18,
                "debt_ratio": 0.35
            }
        }
        
        return {
            "status": "success", 
            "symbol": symbol,
            "data_type": data_type,
            "data": mock_data.get(data_type, {})
        }
    except Exception as e:
        return {"status": "error", "message": str(e)}

@mcp.tool()
def market_sentiment() -> dict:
    """
    市场情绪分析工具
    
    Returns:
        包含市场情绪分析的字典
    """
    try:
        # 模拟市场情绪数据
        sentiment_data = {
            "overall_sentiment": "neutral",
            "fear_greed_index": 45,
            "vix": 18.5,
            "put_call_ratio": 0.85,
            "insider_trading": "neutral",
            "analyst_recommendations": {
                "buy": 60,
                "hold": 30,
                "sell": 10
            }
        }
        
        return {"status": "success", "data": sentiment_data}
    except Exception as e:
        return {"status": "error", "message": str(e)}

# 健康检查端点
@mcp.tool()
def health_check() -> dict:
    """
    健康检查端点
    
    Returns:
        服务健康状态
    """
    return {
        "status": "healthy", 
        "service": "financial-agent-mcp",
        "version": "1.0.0",
        "timestamp": str(asyncio.get_event_loop().time())
    }

# 服务器启动函数
def start_server(host: str = "0.0.0.0", port: int = 8080):
    """
    启动MCP服务器
    
    Args:
        host: 服务器主机地址
        port: 服务器端口
    """
    print(f"Starting Financial Agent MCP Server on {host}:{port}")
    print("Available tools:")
    print("- fundamental_analysis: 公司基本面分析")
    print("- industry_analysis: 行业研究分析")
    print("- macro_analysis: 宏观经济分析")
    print("- market_observation: 市场观察")
    print("- risk_assessment: 投资风险评估")
    print("- investment_advice: 投资建议生成")
    print("- full_analysis: 全流程金融分析")
    print("- get_financial_data: 获取金融数据")
    print("- market_sentiment: 市场情绪分析")
    print("- health_check: 健康检查")
    
    try:
        mcp.run(host=host, port=port)
    except Exception as e:
        print(f"Failed to start MCP server: {e}")
        raise

if __name__ == "__main__":
    # 从环境变量获取端口，默认为8080
    port = int(os.getenv("MCP_PORT", 8080))
    host = os.getenv("MCP_HOST", "0.0.0.0")
    
    start_server(host=host, port=port)